package com.cinema.dao.impl;

import com.cinema.dao.TicketDao;
import com.cinema.db.DatabaseManager;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 售票数据访问实现类
 */
public class TicketDaoImpl implements TicketDao {
    
    private final DatabaseManager dbManager = DatabaseManager.getInstance();
    
    @Override
    public void sellTicket(String scheduleId, int row, int col, String phone, String operatorId) {
        // 检查座位是否已售
        if (isSeatOccupied(scheduleId, row, col)) {
            throw new RuntimeException("座位已售出");
        }
        
        // 更新座位状态
        String updateSeatSql = "UPDATE seat_status SET is_occupied = 1, phone = ?, updated_at = CURRENT_TIMESTAMP WHERE schedule_id = ? AND row_num = ? AND col_num = ?";
        try {
            int rows = dbManager.executeUpdate(updateSeatSql, phone, scheduleId, row, col);
            if (rows == 0) {
                throw new RuntimeException("座位不存在");
            }
        } catch (SQLException e) {
            throw new RuntimeException("更新座位状态失败", e);
        }
        
        // 添加售票记录
        String insertTicketSql = "INSERT INTO ticket_records (schedule_id, row_num, col_num, phone, operator_id) VALUES (?, ?, ?, ?, ?)";
        try {
            dbManager.executeUpdate(insertTicketSql, scheduleId, row, col, phone, operatorId);
        } catch (SQLException e) {
            throw new RuntimeException("添加售票记录失败", e);
        }
    }
    
    @Override
    public boolean isSeatOccupied(String scheduleId, int row, int col) {
        String sql = "SELECT is_occupied FROM seat_status WHERE schedule_id = ? AND row_num = ? AND col_num = ?";
        try (ResultSet rs = dbManager.executeQuery(sql, scheduleId, row, col)) {
            if (rs.next()) {
                return rs.getInt("is_occupied") == 1;
            }
            return false;
        } catch (SQLException e) {
            throw new RuntimeException("检查座位状态失败", e);
        }
    }
    
    @Override
    public boolean[][] getSeatStatus(String scheduleId, int rows, int cols) {
        boolean[][] seatStatus = new boolean[rows][cols];
        String sql = "SELECT row_num, col_num, is_occupied FROM seat_status WHERE schedule_id = ? ORDER BY row_num, col_num";
        
        try (ResultSet rs = dbManager.executeQuery(sql, scheduleId)) {
            while (rs.next()) {
                int row = rs.getInt("row_num");
                int col = rs.getInt("col_num");
                boolean isOccupied = rs.getInt("is_occupied") == 1;
                
                if (row >= 0 && row < rows && col >= 0 && col < cols) {
                    seatStatus[row][col] = isOccupied;
                }
            }
            return seatStatus;
        } catch (SQLException e) {
            throw new RuntimeException("获取座位状态失败", e);
        }
    }
    
    @Override
    public List<TicketRecord> getTicketRecords(String scheduleId) {
        List<TicketRecord> records = new ArrayList<>();
        String sql = "SELECT row_num, col_num, phone, operator_id, sold_at FROM ticket_records WHERE schedule_id = ? ORDER BY sold_at";
        
        try (ResultSet rs = dbManager.executeQuery(sql, scheduleId)) {
            while (rs.next()) {
                int row = rs.getInt("row_num");
                int col = rs.getInt("col_num");
                String phone = rs.getString("phone");
                String operatorId = rs.getString("operator_id");
                String soldAt = rs.getString("sold_at");
                
                records.add(new TicketRecord(row, col, phone, operatorId, soldAt));
            }
            return records;
        } catch (SQLException e) {
            throw new RuntimeException("获取售票记录失败", e);
        }
    }
    
    @Override
    public SeatStatistics getSeatStatistics(String scheduleId) {
        String sql = "SELECT COUNT(*) as total, SUM(CASE WHEN is_occupied = 1 THEN 1 ELSE 0 END) as occupied FROM seat_status WHERE schedule_id = ?";
        
        try (ResultSet rs = dbManager.executeQuery(sql, scheduleId)) {
            if (rs.next()) {
                int total = rs.getInt("total");
                int occupied = rs.getInt("occupied");
                return new SeatStatistics(total, occupied);
            }
            return new SeatStatistics(0, 0);
        } catch (SQLException e) {
            throw new RuntimeException("获取座位统计失败", e);
        }
    }
} 